import { to } from "../../utils/wxapi";
import { RepairType, tree, banner, GetUser, entity } from "../../api/user";
import { err } from "../../utils/console";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    picker: false,
    columns: [{ values: [], defaultIndex: 0 }],
    load: false,
    model_name: "",
    brand_name: "",
    repairlist: [{ children: [{ sel: false, id: "" }] }],
    list: [{ children: [{ sel: false, id: "" }] }],
    item: { children: [{ sel: false, id: "" }] },
    i: 0,
    selid: [""],
    bannerlist: [] as any,
    entitylist: [] as any,
  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    await this.user();
    await Promise.all([
      this.repair(),
      this.treelist(),
      this.banner(),
      this.entity(),
    ]);
  },
  async user() {
    try {
      const res = await GetUser();
      if (res.statusCode === 200) {
        wx.setStorageSync("user", res.data);
      } else {
        err(res.data);
      }
    } catch (error) {
      err(error);
    }
  },
  async banner() {
    try {
      const res = await banner();
      if (res.statusCode === 200) {
        this.setData({ bannerlist: res.data });
      } else {
        err(res.data);
      }
    } catch (error) {
      err(error);
    }
  },
  async repair() {
    try {
      const res = await RepairType();
      if (res.statusCode === 200) {
        wx.setStorageSync("repairlist", res.data);
        res.data.forEach((e: any) => {
          e.sel = false;
          e.children.forEach((v: any) => {
            v.sel = false;
            v.price = "待检测";
          });
        });
        this.setData({
          repairlist: res.data,
          list: res.data,
        });
      } else {
        err(res.data);
      }
    } catch (error) {
      err(error);
    }
  },
  async treelist() {
    try {
      const res = await tree();
      if (res.statusCode === 200) {
        let list = res.data;
        list.forEach((e: any) => {
          e.models.forEach((e: any) => {
            e.title = e.model_name;
          });
        });
        const columns: { values: any; defaultIndex: number }[] = [
          { values: list, defaultIndex: 0 },
          { values: list[0]?.models || [], defaultIndex: 0 },
        ];
        this.setData({ columns });
      } else {
        err(res.data);
      }
    } catch (error) {
      err(error);
    }
  },
  async entity() {
    try {
      const res = await entity();
      console.log(res);
      if (res.statusCode === 200) {
        this.setData({ entitylist: res.data });
      } else {
        err(res.data);
      }
    } catch (error) {
      err(error);
    }
  },
  upimgs(e: any) {
    const { src } = e.currentTarget.dataset;
    wx.previewImage({
      current: src,
      urls: [src],
    });
  },
  onChange(e: any) {
    try {
      const { value } = e.detail;
      const i = this.findIndexById(this.data.columns[0].values, value[0].id);
      const columns = [...this.data.columns];
      if (i >= 0) {
        const modelItem = this.data.columns[0].values[i] as { models?: any };
        if (modelItem.models) {
          columns[1].values = modelItem.models;
        }
      }
      this.setData({ columns });
    } catch (error) {
      err(error);
    }
  },
  findIndexById(arr: { id: number }[], targetId: number): number {
    return arr.findIndex((item) => item.id === targetId);
  },
  require() {
    this.setData({ picker: true });
  },
  onClose() {
    this.setData({ picker: false });
  },
  onConfirm(e: any) {
    const { value } = e.detail;
    const typelist = this.data.list;
    let model_name;
    let brand_name;
    let repairlist: any[] = [];
    if (value.length > 1) {
      brand_name = value[0].title;
      model_name = value[value.length - 1].title;
      const price = value[value.length - 1].repair_type_price;
      Object.entries(price).forEach(([k, v]) => {
        const typeitem = typelist.find((e: any) => e.id == k);
        if (typeitem) {
          repairlist.push(typeitem);
        } else {
          repairlist.forEach((b: any) => {
            let bitem = b.children && b.children.find((a: any) => a.id == k);
            if (bitem) {
              bitem.price = v;
            }
          });
        }
      });
    }
    this.setData({ picker: false, model_name, brand_name, repairlist });
  },
  add(e: any) {
    const { item, i } = e.currentTarget.dataset;
    this.setData({ item, i, show: true });
  },
  sel(e: any) {
    const { seli } = e.currentTarget.dataset;
    let { repairlist, i } = this.data;
    const a = repairlist[i].children.map((i, index) => ({
      ...i,
      sel: index === seli ? !i.sel : false,
    }));
    repairlist[i].children = a;
    const items = this.data.item.children.map((i, index) => ({
      ...i,
      sel: index === seli ? !i.sel : false,
    }));
    this.setData({ "item.children": items, repairlist });
  },
  sub() {
    const { repairlist, selid } = this.data;
    repairlist.forEach((e: any) => {
      e.sel = false;
      e.children.forEach((v: { sel: boolean; id: string }) => {
        if (v.sel === true) {
          e.sel = true;
          selid.push(v.id);
        }
      });
    });
    this.setData({ repairlist, show: false, selid });
  },
  cancel() {
    this.setData({ show: false });
  },
  tohtc() {
    to("/pages/htc/htc");
  },
  towine() {
    to("/pages/wine/wine");
  },
  ask() {
    const { brand_name, model_name, repairlist } = this.data;
    let repair_type_id: any[] = [];
    repairlist.forEach((e: any) => {
      if (e.sel) {
        e.children.forEach((v: any) => {
          if (v.sel) {
            repair_type_id.push(v.id);
          }
        });
      }
    });
    wx.setStorageSync("fault_list", repairlist);
    wx.setStorageSync("brand_name", brand_name);
    wx.setStorageSync("model_name", model_name);
    wx.setStorageSync("repair_type_id", repair_type_id);
    const user = wx.getStorageSync("user");
    if (user.phone) {
      to("/pages/pay/pay");
    } else {
      to("/pages/login/login");
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
